import sys
import threading
import time
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                           QPushButton, QTextEdit)
from PyQt6.QtCore import pyqtSignal, QObject

class ThreadSignals(QObject):
    """用于从线程发送信号到UI"""
    status = pyqtSignal(str)

class ThreadController:
    def __init__(self, signals):
        self.condition = threading.Condition()
        self.is_running = True
        self.signals = signals
    
    def worker_function(self):
        """线程执行的函数"""
        while self.is_running:
            # 阻塞线程
            with self.condition:
                self.signals.status.emit("线程已阻塞")
                self.condition.wait()  # 线程阻塞
                print(1234)
            
            # 线程被释放后执行
            self.signals.status.emit("线程被释放，正在执行...")
            time.sleep(1)  # 模拟工作
            
            # 自动重新阻塞
            self.signals.status.emit("等待1秒后重新阻塞...")
            time.sleep(1)  # 等待1秒
    
    def release_thread(self):
        """释放线程"""
        with self.condition:
            self.condition.notify()
    
    def stop(self):
        """停止线程"""
        self.is_running = False
        self.release_thread()  # 确保线程能够退出

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 先创建signals
        self.signals = ThreadSignals()
        self.thread_controller = None
        self.worker_thread = None
        # 然后初始化UI
        self.init_ui()
    
    def init_ui(self):
        self.setWindowTitle("线程控制示例")
        self.setGeometry(100, 100, 400, 300)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        
        # 创建控件
        self.text_edit = QTextEdit()
        self.start_button = QPushButton("启动线程")
        self.release_button = QPushButton("释放线程")
        self.stop_button = QPushButton("停止线程")
        
        # 添加控件到布局
        layout.addWidget(self.text_edit)
        layout.addWidget(self.start_button)
        layout.addWidget(self.release_button)
        layout.addWidget(self.stop_button)
        
        # 设置按钮初始状态
        self.release_button.setEnabled(False)
        self.stop_button.setEnabled(False)
        
        # 连接信号
        self.start_button.clicked.connect(self.start_thread)
        self.release_button.clicked.connect(self.release_thread)
        self.stop_button.clicked.connect(self.stop_thread)
        self.signals.status.connect(self.update_status)
    
    def start_thread(self):
        if not self.thread_controller:
            # 创建线程控制器
            self.thread_controller = ThreadController(self.signals)
            
            # 创建并启动工作线程
            self.worker_thread = threading.Thread(
                target=self.thread_controller.worker_function
            )
            self.worker_thread.start()
            
            # 更新按钮状态
            self.start_button.setEnabled(False)
            self.release_button.setEnabled(True)
            self.stop_button.setEnabled(True)
            self.update_status("线程已启动")
    
    def release_thread(self):
        if self.thread_controller:
            self.thread_controller.release_thread()
            self.release_button.setEnabled(True)
    
    def stop_thread(self):
        if self.thread_controller:
            self.thread_controller.stop()
            self.worker_thread.join()
            self.thread_controller = None
            self.worker_thread = None
            
            # 更新按钮状态
            self.start_button.setEnabled(True)
            self.release_button.setEnabled(False)
            self.stop_button.setEnabled(False)
            self.update_status("线程已停止")
    
    def update_status(self, message):
        current_time = time.strftime("%H:%M:%S")
        self.text_edit.append(f"{current_time} - {message}")
        # 滚动到底部
        self.text_edit.verticalScrollBar().setValue(
            self.text_edit.verticalScrollBar().maximum()
        )

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()
